package com.cugmarket.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cugmarket.entity.ProductVoucher;
import com.cugmarket.entity.VoucherOrder;
import com.cugmarket.exception.BaseException;
import com.cugmarket.service.ProductVoucherService;
import com.cugmarket.service.VoucherOrderService;
import com.cugmarket.mapper.VoucherOrderMapper;
import com.cugmarket.utils.RedisIdWorker;
import com.cugmarket.utils.SimpleRedisLock;
import com.cugmarket.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* @author duoch
* @description 针对表【voucher_order】的数据库操作Service实现
* @createDate 2024-11-05 15:38:23
*/
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder>
    implements VoucherOrderService{
    @Resource
    private ProductVoucherService productVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    //异步处理线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();
    //在类初始化之后执行，因为当这个类初始化好了之后，随时都是有可能要执行的
    @PostConstruct
    private void init() {
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    //阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    //1. 获取队列中的订单信息
                    VoucherOrder voucherOrder = orderTasks.take();
                    handleVoucherOrder(voucherOrder);
                    //2. 创建订单
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                }
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        // 1.获取用户
        String userId = voucherOrder.getUserId();
        // 2.创建锁对象
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        // 3.获取锁
        boolean isLock = lock.tryLock();
        // 4.判断是否获取锁成功
        if (!isLock) {
            // 获取锁失败，返回错误或重试
            log.error("不允许重复下单");
            return;
        }
        try{
//            proxy.createVoucherOrder(voucherOrder);
            createVoucherOrder(voucherOrder);
        }finally {
            // 释放锁
            lock.unlock();
        }
    }

    private VoucherOrderService proxy;
    @Override
    public String sekillVoucher(String voucherId) {
        String userId = UserHolder.getUser();
        long orderId = redisIdWorker.uniqueId("order");
        //1.执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId, userId, String.valueOf(orderId)
        );
        //2.判断结果是否为0
        int r = result.intValue();
        if (r != 0) {
            //2.1 不为0，代表没有购买资格
            throw new BaseException(r == 1 ? "库存不足" : "不能重复下单");
        }
        // 3.创建订单
        ProductVoucher productVoucher = productVoucherService.getById(voucherId);
        VoucherOrder voucherOrder = new VoucherOrder();
        // 3.1.订单id
        voucherOrder.setId(String.valueOf(orderId));
        // 3.2.用户id
        voucherOrder.setUserId(userId);
        // 3.3.代金券id
        voucherOrder.setVoucherId(voucherId);
        // 3.4.商品id
        voucherOrder.setProductId(productVoucher.getProductId());
        // 3.5.优惠券状态
        voucherOrder.setStatus(productVoucher.getVoucherStatus());
        // 3.6.优惠额度
        voucherOrder.setVoucherValue(productVoucher.getVoucherValue());
        // 3.7.放入阻塞队列
        orderTasks.add(voucherOrder);
        //4.获取代理对象
//        proxy = (VoucherOrderService)AopContext.currentProxy();
        //5.返回订单id
        return String.valueOf(orderId);

    }
    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        System.out.println(111);
        String voucherId = voucherOrder.getVoucherId();
        // 5.一人一单逻辑
        // 5.1.用户id
        String userId = UserHolder.getUser();
        Long count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        // 5.2.判断是否存在
        if (count > 0) {
            // 用户已经购买过了
            throw new BaseException("用户已经购买过一次");
        }
        // 6.扣减库存
        boolean success = productVoucherService.update()
                .setSql("stock= stock -1")
                .eq("id", voucherId)
                .gt("stock", 0)
                .update();
        ; //where id = ? and stock > 0
        if (!success) {
            throw new BaseException("库存不足");
        }
        //8.新增订单
        save(voucherOrder);
    }
}




